<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="cancel-btn" @click="handleCancel">取消</text>
      <text class="title">选择城市</text>
      <text class="confirm-btn" @click="handleConfirm">确认</text>
    </view>

    <!-- 主要内容区 -->
    <view class="main-content">
      <!-- 左侧地区分类 -->
      <scroll-view class="region-list" scroll-y>
        <view 
          class="region-item" 
          :class="{ active: currentRegionLevel === 'province' }"
          @click="switchRegionLevel('province')"
        >
          <text class="region-label">省份</text>
          <text class="region-value">
            {{ selectedProvince && selectedProvince.regionName || '请选择' }}
          </text>
        </view>
        <view 
          class="region-item" 
          :class="{ active: currentRegionLevel === 'city' }"
          @click="switchRegionLevel('city')"
          :style="{ 
            pointerEvents: !selectedProvince ? 'none' : 'auto', 
            opacity: !selectedProvince ? 0.5 : 1 
          }"
        >
          <text class="region-label">市/县</text>
          <text class="region-value">
            {{ selectedCity && selectedCity.regionName || '请选择' }}
          </text>
        </view>
      </scroll-view>

      <!-- 右侧区域选择 -->
      <scroll-view class="area-content" scroll-y>
        <view v-if="currentRegionLevel === 'province'" class="area-grid">
          <view 
            class="area-btn" 
            v-for="province in provinces" 
            :key="province.regionId"
            :class="{ selected: selectedProvince && selectedProvince.regionId === province.regionId }"
            @click="selectProvince(province)"
          >
            {{ province.regionName }}
          </view>
        </view>
        
        <view v-else class="area-grid">
          <view 
            class="area-btn" 
            v-for="city in cities" 
            :key="city.regionId"
            :class="{ selected: selectedCity && selectedCity.regionId === city.regionId }"
            @click="selectCity(city)"
          >
            {{ city.regionName }}
          </view>
          
          <view v-if="loadingCities" class="loading-state">加载中...</view>
          <view v-if="!loadingCities && cities.length === 0" class="empty-state">暂无数据</view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部导航按钮 -->
    <view class="footer">
      <!-- 条件渲染：省份阶段显示「清空」，市/县阶段显示「上一步」 -->
      <button 
        v-if="currentRegionLevel === 'province'" 
        class="prev-or-clear-btn-red" 
        @click="handleClearRegion"
      >
        清空地区选择
      </button>
      <button 
        v-else 
        class="prev-or-clear-btn" 
        @click="handlePrev"
      >
        上一步
      </button>
      <button class="next-btn" @click="handleNext" :disabled="!canGoNext">下一步</button>
    </view>
  </view>
</template>

<script>
import { 
  getPositionTypeAndFirst, 
  getCountiesByProvinceId, 
  updateCareerExpectationRegion ,
  updateCareerExpectationRegionIsNull
} from '@/api/user.js'

export default {
  data() {
    return {
      currentRegionLevel: 'province', // 'province' 或 'city'
      selectedProvince: null,          // 选中的省份对象
      selectedCity: null,              // 选中的市/县对象
      provinces: [],                   // 所有省份数据
      cities: [],                      // 当前选中省份的市/县数据
      loadingCities: false             // 市县数据加载状态
    };
  },
  computed: {
    // 判断是否可以进入下一步
    canGoNext() {
      if (this.currentRegionLevel === 'province') {
        return !!this.selectedProvince;
      }
      return !!this.selectedCity;
    }
  },
  onLoad() {
    // 获取省份数据
    this.getProvinces();
  },
  methods: {
    // 获取省份数据
    getProvinces() {
      getPositionTypeAndFirst().then(res => {
        this.provinces = res.data.regionDOS || [];
      }).catch(err => {
        console.error('获取省份数据失败:', err);
        uni.showToast({ title: '获取省份失败', icon: 'none' });
      });
    },
    
    // 获取市县数据 - 根据省份ID获取市县
    getCities(provinceId) {
      if (!provinceId) return;
      
      this.loadingCities = true;
      this.cities = [];
      
      getCountiesByProvinceId({ ProvinceId: provinceId }).then(res => {
        this.cities = res.data || [];
      }).catch(err => {
        console.error('获取市县数据失败:', err);
        uni.showToast({ title: '获取市县失败', icon: 'none' });
      }).finally(() => {
        this.loadingCities = false;
      });
    },
    
    // 切换地区级别（省份/市/县）
    switchRegionLevel(level) {
      if (level === 'city' && !this.selectedProvince) return;
      this.currentRegionLevel = level;
      
      // 如果切换到市/县级别且没有加载过数据，则加载
      if (level === 'city' && this.cities.length === 0) {
        this.getCities(this.selectedProvince.regionId);
      }
    },
    
    // 选择省份
    selectProvince(province) {
      this.selectedProvince = province;
      this.selectedCity = null;
      this.cities = [];
      this.getCities(province.regionId);
    },
    
    // 选择市/县
    selectCity(city) {
      this.selectedCity = city;
    },
    
    // 上一步（仅在市/县阶段显示）
    handlePrev() {
      if (this.currentRegionLevel === 'city') {
        this.currentRegionLevel = 'province';
      }
    },
    
    // 下一步
    handleNext() {
      if (this.currentRegionLevel === 'province' && this.selectedProvince) {
        this.currentRegionLevel = 'city';
      } else if (this.currentRegionLevel === 'city' && this.selectedCity) {
        this.handleConfirm();
      }
    },
    
    // 取消选择
    handleCancel() {
      uni.navigateBack();
    },
    
    // 确认选择
    handleConfirm() {
      if (!this.selectedCity) {
        uni.showToast({ title: '请选择市/县', icon: 'none' });
        return;
      }
      const expectId = uni.getStorageSync("expectId")
      if (expectId == 0) {
        let recruitInfoVO = uni.getStorageSync("RecruitInfoVO");
        try {
          recruitInfoVO = typeof recruitInfoVO === 'string' 
            ? JSON.parse(recruitInfoVO) 
            : (recruitInfoVO || {});
        } catch (e) {
          recruitInfoVO = {};
          console.error('解析RecruitInfoVO失败:', e);
        }
        recruitInfoVO.regionId = this.selectedCity.regionId;
        uni.setStorageSync("RecruitInfoVO", recruitInfoVO)
        uni.$emit('mainPageRefresh');
        uni.switchTab({ url: '/pages/zcy/main' });
      } else {
        updateCareerExpectationRegion({ 
          expectId: expectId, 
          regionId: this.selectedCity.regionId 
        }).then(res => {
          uni.$emit('mainPageRefresh');
          uni.switchTab({ url: '/pages/zcy/main' });
        });
      }
    },
    
    // 清空地区选择（添加弹窗确认）
    handleClearRegion() {
      // 弹窗确认是否清空
      uni.showModal({
        title: '确认清空',
        content: '确定要清空已选择的地区吗？',
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          // 用户点击确定后执行清空逻辑
          if (res.confirm) {
            const expectId = uni.getStorageSync("expectId")
            if (expectId == 0) {
              let recruitInfoVO = uni.getStorageSync("RecruitInfoVO");
              try {
                recruitInfoVO = typeof recruitInfoVO === 'string' 
                  ? JSON.parse(recruitInfoVO) 
                  : (recruitInfoVO || {});
              } catch (e) {
                recruitInfoVO = {};
                console.error('解析RecruitInfoVO失败:', e);
              }
              recruitInfoVO.regionId = null;
              uni.setStorageSync("RecruitInfoVO", recruitInfoVO)
              // 重置本地选择状态
              this.selectedProvince = null;
              this.selectedCity = null;
              this.cities = [];
              uni.$emit('mainPageRefresh');
              uni.switchTab({ url: '/pages/zcy/main' });
            } else {
              updateCareerExpectationRegionIsNull({ 
                expectId: expectId, 
              }).then(res => {
                // 重置本地选择状态
                this.selectedProvince = null;
                this.selectedCity = null;
                this.cities = [];
                uni.$emit('mainPageRefresh');
                uni.switchTab({ url: '/pages/zcy/main' });
              });
            }
          }
          // 用户取消则不执行任何操作
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}
.title { font-size: 18px; font-weight: bold; }
.cancel-btn { font-size: 16px; color: #666; }
.confirm-btn { font-size: 16px; color: #07C160; }

/* 主要内容区 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.prev-or-clear-btn-red{
  flex: 1;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 10px;
  background-color: #f5092d;
  color: white; /* 修正文字颜色为白色，与红底更搭配 */
}
.prev-or-clear-btn-red:active {
  background-color: #d40827; /* 点击时加深红色 */
}

/* 左侧地区列表 */
.region-list {
  width: 30%;
  background-color: #f8f8f8;
}
.region-item {
  padding: 15px;
  font-size: 14px;
  border-bottom: 1px solid #eee;
}
.region-item.active {
  background-color: #1890ff;
  color: white;
}
.region-item.active .region-value {
  color: rgba(255, 255, 255, 0.9);
}
.region-label { 
  display: block; 
  font-weight: bold; 
}
.region-value { 
  color: #666; 
  font-size: 12px; 
  margin-top: 5px; 
}

/* 右侧区域内容 */
.area-content {
  width: 70%;
  padding: 15px;
}
.area-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}
.area-btn {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  font-size: 14px;
}
.area-btn.selected {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}
.loading-state, .empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 底部导航按钮 */
.footer {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

/* 上一步/清空 按钮复用样式 */
.prev-or-clear-btn {
  flex: 1;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 10px;
  background-color: #f5f5f5;
  color: #333;
}
.prev-or-clear-btn:active {
  background-color: #e6e6e6;
}

.next-btn {
  flex: 1;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 14px;
  margin-left: 10px;
  background-color: #1890ff;
  color: white;
}
.next-btn:disabled {
  background-color: #ccc;
  color: #fff;
  opacity: 0.7;
}
</style>